package com.example.softwareengg;




import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.StringTokenizer;

import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.content.Intent;


public class ScreenDownload extends HeaderFooter implements OnClickListener   {
	static String serverIP = "10.20.1.251";
	static String filename;
    private static final int REQUEST_PICK_FILE = 1;

    private TextView mFilePathTextView;
    private Button mStartActivityButton;
    private File selectedFile;
    

	@Override 
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewGroup vg = (ViewGroup) findViewById(R.id.lldata);
        ViewGroup.inflate(ScreenDownload.this, R.layout.screendownload, vg);
        mFilePathTextView = (TextView)findViewById(R.id.file_path_text_view);
        Button yes = (Button)findViewById(R.id.yes);
        Button no = (Button)findViewById(R.id.no);
         TextView textdownload = (TextView)findViewById(R.id.textdownload);
        TextView userName1 = (TextView)findViewById(R.id.textUsername);
		 //Intent i1 = getIntent();
		String shruti2 = "Welcome " +MyOverridenApp.getUser();

		TextView ResHead = (TextView) findViewById(R.id.reshead);
		TextView textviewdown = (TextView)findViewById(R.id.textdownload);
		textviewdown.setText(MyOverridenApp.getfilenametobedownloaded());
		SpannableString content1 = new SpannableString("Download");
		SpannableString content2 = new SpannableString(shruti2);
		content1.setSpan(new UnderlineSpan(), 0, content1.length(), 0);
		content2.setSpan(new UnderlineSpan(), 0, content2.length(), 0);
		userName1.setText(content2);
		ResHead.setText(content1);
	
		
		
		
		yes.setOnClickListener(this);
		no.setOnClickListener(this);
		Button button_logout = (Button) findViewById(R.id.Button_logout);
		Button home = (Button)findViewById(R.id.home);
		
		button_logout.setOnClickListener(this);
		home.setOnClickListener(this);
		
	}
	public void onClick(View v) {
        switch (v.getId()) {
        
        case R.id.home:
        {
			   Intent intent = new Intent(ScreenDownload.this,ScreenB.class);
			    startActivity(intent);
			    break;

        }
      	        case R.id.no:
      	        {
      	        	
      	        	Intent intent = new Intent(ScreenDownload.this,ScreenB.class);
				    startActivity(intent);
				    break;
      	        	
      	            

      	        //ase R.id.You_can_handle_more_onclick_events_from_here:
      	            //Do something
      	            //break;

      	        }
      	      case R.id.Button_logout:
  	        {
  	        	try{
  	        		Toast.makeText(getApplicationContext(),"Logout", Toast.LENGTH_LONG).show();
  	        		
  	        	Socket client = MyOverridenApp.getClient();
  	        	DataOutputStream outToServer = new DataOutputStream(client.getOutputStream());
  				
  				outToServer.writeBytes("signout\n");
  				client.close();
  				}
  	        	catch(Exception e){
  	        		e.printStackTrace();
  	        		Toast.makeText(getApplicationContext(),"Error Logging out", Toast.LENGTH_LONG).show();
  	        		
  	        	}
  				   Intent intent = new Intent(ScreenDownload.this,ScreenA.class);
  				    startActivity(intent);
  				    break;

  	        }

      	        case R.id.yes:
      	        {
    	       		BufferedInputStream d = null;
    	       		BufferedOutputStream outStream =null;
      	        	//filename = ((EditText)findViewById(R.id.editupload)).getText().toString();
    	       		
    	       		StringTokenizer x = new StringTokenizer(MyOverridenApp.getfilenametobedownloaded());
    	       		String userdown = new String(x.nextToken());
    	       		x.nextToken();
    	       		x.nextToken();
    	       		
    	       		filename = x.nextToken();
      	        	try {
						 Socket client = MyOverridenApp.getClient();
						DataOutputStream outToServer = new DataOutputStream(client.getOutputStream());
						
						outToServer.writeBytes("download "+filename+" "+userdown+"\n");
						
					
						d=new BufferedInputStream(client.getInputStream());
		                FileOutputStream fos = new FileOutputStream("/mnt/sdcard/"
		                        +filename);
		                
		                outStream = new BufferedOutputStream(fos);
		            
		                byte buffer[] = new byte[1025];
		   	         int read;
		   	        
		   	         while((read = d.read(buffer))!=-1)
		   	         {//read = d.read(buffer);
		   	        	 System.out.println("--------------------------");
		   	             outStream.write(buffer, 0, read);
		   	             outStream.flush();
		   	             buffer=new byte[1025];
		   	            // curent=curent+read;
		   	          //   System.out.println(" "+read);
		   	             if(read<1025)
		   	            	 break;
		   	         }
		   	         
		   	         fos.close();
		   	        outStream.close();
		                mFilePathTextView.setText("/mnt/sdcard/"+filename); 
		            } catch (IOException e) {
		                Toast.makeText(getApplicationContext(),
		                        "Failed to download the file!", Toast.LENGTH_LONG)
		                        .show();
		            }
      	        	
      	        	
                    // Set the file path text view
                     
                    	

	 }
      	        }
        }
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
        if(resultCode == RESULT_OK) {
            switch(requestCode) {
            case REQUEST_PICK_FILE:
                if(data.hasExtra(FilePickerActivity.EXTRA_FILE_PATH)) {
                    // Get the file path
                    selectedFile = new File(data.getStringExtra(FilePickerActivity.EXTRA_FILE_PATH));
                    // Set the file path text view
                    mFilePathTextView.setText(selectedFile.getPath()); 
                    
                    
                    
                   
										    
                    //System.out.println(selectedFile.getPath().toString());
                    //System.out.println(selectedFile.getAbsolutePath().toString());
                    //Now you have your selected file, You can do your additional requirement with file.                
                }
            }
        }
    }

	@Override
	public void onBackPressed() {
	}
}